package com.hbnulk.test;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;

public class MyFrame3 extends JFrame implements KeyListener {
    public MyFrame3() {
        //设置界面的宽高
        this.setSize(603, 680);
        //设置标题
        this.setTitle("测试键盘监听按键");
        //设置界面置顶
        this.setAlwaysOnTop(true);
        //设置界面加载后居中
        this.setLocationRelativeTo(null);
        //设置关闭模式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //取消默认的居中放置，取消才会按照XY形式放置组件
        this.setLayout(null);

        //给整个窗体添加键盘监听
        this.addKeyListener(this);

        //让界面显示出来
        this.setVisible(true);
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("按下不松");
    }

    @Override
    public void keyReleased(KeyEvent e) {
        System.out.println("松下按键");
        int keyCode = e.getKeyCode();
        if(keyCode == 65){
            System.out.println("按下的是A键");
        }else if(keyCode == 66){
            System.out.println("按下的是B键");
        }else{
            System.out.println("按下的是其他键");
        }
    }
}